$(function(){
    //$.sme.cbk.ajaxUserMenuItem();
    //$.sme.init.ajaxMenuItemHistory();
    $.sme.init.registerAjaxCallbacks();
    $.sme.init.justifyPainator();
    $.sme.init.initWidgets();
    $.sme.init.justifyTables();
    $.sme.init.flashMessage();
});

// Tomato self defind functions, callbacks, etc
;(function($){
$.sme = {};
// Define the global namespace, $.sme
$.extend($.sme, {
    k: function(){},       // Empty function
    cache: {},                // Cached elements, and data
    cbk: {},                    // Module action callbacks
    data: {},                  // Data holder
    fn: {},                       // Utility functions
    init: {},                    // Page initialize functions
    inits: [],                   // Holder all names of initialize functions
    option: {},              // Options holder, for ajax, animations
    status: {},              // Options holder, for ajax, animations
    timer: {},                 // Timer holder
    url: {}                       // Ajax request url prefixes
});

// Define some ajax request url constructors
$.sme.url.base = 'http://localhost/tests/sme';
$.extend($.sme.url, {
    user: function(action){ return $.sme.url.base+'/users/'+action+'/'; },
    post: function(action){ return $.sme.url.base+'/posts/'+action+'/'; },
    post_term: function(action){ return $.sme.url.base+'/post_terms/'+action+'/'; },
    post_attachment: function(action){ return $.sme.url.base+'/post_attachments/'+action+'/'; },
    student: function(action){ return $.sme.url.base+'/students/'+action+'/'; },
    company: function(action){ return $.sme.url.base+'/companies/'+action+'/'; },
    company_industry: function(action){ return $.sme.url.base+'/company_industries/'+action+'/'; },
    company_location: function(action){ return $.sme.url.base+'/company_locations/'+action+'/'; },
    company_type: function(action){ return $.sme.url.base+'/company_types/'+action+'/'; }
});

// Webpage initialize functions
$.extend($.sme.init, {
    // Ajax loading for page contents when click meta links
    ajaxMenuItemHistory: function(){
        $.historyInit($.sme.cbk.ajaxMenuItemLoad);
        $('a.user_menu_item').click(function(event){
            event.preventDefault();
            $.sme.data.menu = $(this);
            var hash = this.href;
            hash = hash.replace(/^.*#/, '');
            $.historyLoad(hash);
            return false;
        });
    },
    // Register global ajax callbacks
    registerAjaxCallbacks: function(){
        $('span.notifier').hide()
            .ajaxStart(function(){
                var msg = $.sme.ajaxStart || '正在加载, 稍后';
                $('span.notifier').attr('class', 'notifier load').text(msg).show();
            })
            .ajaxError($.sme.cbk.ajaxError);
    },
    // Justift Paginator
    justifyPainator: function(){
        $('div.paging a:empty').remove();
    },
    // Initialize widgets, from app/views/posts/add.ctp
    initWidgets: function(){
        // Bind widget hover actions
        $('div.widget').hover(function(){
            $(this).children('div.toggle').addClass('hover');
        }, function(){
            $(this).children('div.toggle').removeClass('hover');
        });
        // Bind widget toggler actions
        $('div.widget div.toggle').click(function(){
            $(this).nextAll('div.content').slideToggle(200);
        });
    },
    // Justify table headers for translation
    justifyTables: function(){
        $('th:contains(Workplace)').text('工作地点');
        $('th:contains(Clicks)').text('点击量');
        $('th:contains(Company)').text('所属公司');
        $('#table_jobs th:contains(Students Job Count)').text('StudentCount');
    },
    // Notify users of server side session flash messages
    flashMessage: function(){
        var elm = $('#flashMessage'), text = elm.text();
        if(elm.length && (text != '')){
            elm.remove();
            $.sme.fn.notify('notice', text);
        }
        var elm = $('#authMessage'), text = elm.text();
        if(elm.length && (text != '')){
            elm.remove();
            var type = 'notice';
            if(text.indexOf('对不起') >= 0){
                type = 'error';
            }
            $.sme.fn.notify(type, text);
        }
    }
});

// User interactive callbacks
$.extend($.sme.cbk, {
    // Ajax start notification
    ajaxStart: function(content){
        var content = content || $.sme.ajaxStart || '正在加载, 稍后';
        $.sme.notify('load', content);
    },
    // Ajax success callback
    ajaxSuccess: function(content){
        var content = content || '设置已保存';
        $.sme.notify('success', content);
    },
    // Ajax error callback
    ajaxError: function(content){
        var content = content || '糟糕, 请求出错啦';
        $.sme.notify('error', content);
    },
    // New callback for Ajax History Page Loading
    ajaxMenuItemLoad: function(hash){
        if(hash){
            if($.browser.msie){
                hash = encodeURIComponent(hash);
            }
            if($.sme.data.hash == hash){
                $.log('Current Page is loaded and visible, just return');
                return false;
            }
            $.sme.data.hash = hash;
            $.log('Loading ajax history page #'+hash);
            $.ajax({
                global: false,
                url: hash,
                complete: $.sme.cbk.ajaxMenuItemLoadComplete
            });
        }
    },
    // Ajax tab load complete callbacks
    ajaxMenuItemLoadComplete: function(xhr){
        $('#column_right').html(xhr.responseText);
    },
    // Ajax check for unique fields
    ajaxCheck: function(){
        /* this[options] = {
                label: the label for message display
                input: the field to be checked for
                id: input id to check for fields
                model: Server side model name
                fielden: Database table field name
                fieldzh: field name in Chinese
                control: Data cacke key such as: post_term, company_type
        */
        if(this.input.attr('id') == this.id){
            var value = this.input.val(), data = {},
                label = this.label, fieldzh = this.fieldzh, fielden = this.fielden,
                control = this.control, model = this.model;
            data[this.fielden] = value;
            if(value != $.sme.data[this.control]){
                $.log('Check for '+model+'.'+fielden+' with #'+value);
                $.sme.data[this.control] = value;
                $.ajax($.extend($.sme.option.json, {
                    data: $.sme.datas(data, this.model),
                    url: $.sme.url[this.control]('check'),
                    beforeSend: function(){
                        label.addClass('load').html('检查'+fieldzh+', 稍后').nextAll('label.success').remove();
                    },
                    success: function(json){
                        $.sme.status[control] = json.status;
                        if(json.status){
                            $.log(model+'.'+fielden+'('+value+') not taken, useable');
                            label.attr('class', 'success').attr('id', $.time())
                                .html(fieldzh+'<strong>'+$.sme.data[control]+'</strong>可用')
                                .prev('input').addClass('success');
                        }else{
                            $.log(model+'.'+fielden+'('+value+') taken, please choose another');
                            label.attr('class', 'error')
                                .html(fieldzh+'<strong>'+$.sme.data[control]+'</strong>已存在')
                                .prev('input').addClass('error');
                        }
                    }
                }));
            }else{
                label.remove();
            }
        }else{
            label.remove();
        }
    },
    // Apply for a job via ajax request
    ajaxApply: function(event){
        $.sme.ajaxStart = '正在处理您的请求, 稍后';
        $.sme.json.apply(this, [event]);
    },
    /* Delete job application using ajax request */
    ajaxAntiApply: function(event){
        $.sme.ajaxStart = '正在取消职位申请, 请稍后';
        $.sme.json.apply(this, [event, function(json){
            if(json.status){
                this.parents('tr').css('background-color', '#ffe600').fadeOut(2000, function(){
                    $(this).remove();
                });
            }
        }]);
    },
    // Delete a data record via ajax request
    ajaxDelete: function(event){
        $.sme.ajaxStart = '正在删除数据及其相关信息, 稍后';
        $.sme.json.apply(this, [event, function(json){
            if(json.status){
                this.parents('tr').fadeOut(2000, function(){
                    $(this).remove();
                });
            }
        }]);
    },
    // Init User menus, from app/views/elements/menu_user_admin.ctp;
    initUserMenu: function(){
        // Cookie support on revision 58
        // Hide All Subment list on page initialze
        $('div.submenu').hide();
        // Add hover actions for toggle divisions
        $('ul.menu li.item:has(div.submenu)').hover(function(){
            $(this).children('div.toggle').addClass('hover');
        }, function(){
            $(this).children('div.toggle').removeClass('hover');
        });
        // Add click actions for toggle divisions
        $('ul.menu li.item').data('sme.status.current', false);
        $('div.toggle').click(function(){
            var element = $(this);
            element.nextAll('div.submenu').slideToggle(200, function(){
                var parent = element.parent('li.item');
                if(parent.data('sme.status.current') === true){
                    parent.removeClass('current').data('sme.status.current', false);
                }else{
                    parent.addClass('current').data('sme.status.current', true);
                }
            });
        });
        // Show some one that matches current location hash
        $('div.submenu:has(li a[href='+window.location.pathname+'])').show()
            .parent('li.item').addClass('current');
    },
    // Initialize CKEditor instance for elements
    initCKEditor: function(id, toolbar){
        if(!$('#'+id).length) return false;
        var toolbar = toolbar || 'ckeditor';
        $.log('Init CKEditor for field #'+id);
        CKEDITOR.replace(id, $.sme.option[toolbar]);
    }
});

// Utility functions
$.extend($.sme.fn, {
    // System message boadcast system for ajax activities, form validations
    notify: function(type, msg){
        $('span.notifier')
            .attr('class', 'notifier '+type)
            .text(msg)
            .fadeIn(500, function(){
                setTimeout(function(){
                    $('span.notifier').fadeOut();
                }, 3000);
            });
    },
     // Auto notify, this is usally used when an json request complete
    autoNotify: function(json){
        $.sme.cbk[json.status ? 'ajaxSuccess' : 'ajaxError'](json.code);
    },
    // Handles json requests and responders
    json: function(event, callback){
        event.preventDefault();
        var link = $(this), callback = $.isFunction(callback) ? callback : $.sme.k;
        $.ajax($.extend($.sme.option.json, {
            type: 'get',
            url: link.attr('href'),
            success: function(json){
                $.sme.autoNotify(json);
                $.log(json);
                callback.apply(link, [json]);
            }
        }));
    },
    // Process data as CakePHP firendly format
    datas: function(object, model){
        var data = {};
        var model = model || 'User';
        for(var index in object){
            data['data['+model+']['+index+']'] = object[index];
        }
        return data;
    }
});

// Global options
$.extend($.sme.option, {
    html: {
        type: 'post',
        global: true,
        dataType: 'html'
    },
    json: {
        type: 'post',
        global: true,
        dataType: 'json'
    },
    ckeditor: {
        language: 'zh-cn',
        resize_enabled: false,
        toolbar: [
            ['Save','NewPage','Preview', '-', 'Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', '-', 'Maximize', 'ShowBlocks','-','About'],
            ['Link','Unlink','Anchor', '-', 'Image','Table','HorizontalRule'],
            ['Bold','Italic','Underline','Strike', '-','NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            '/',
            ['Styles','Format','Font','FontSize', '-','TextColor','BGColor','-'],
        ]
    },
    basic: {
        language: 'zh-cn',
        resize_enabled: false,
        toolbar: 'Basic'
    },
    span: $('<span class="indicator">正在加载, 稍后</span>')
});

$.extend($.sme, $.sme.fn);

})(jQuery);
